import matplotlib.pyplot as plt
import numpy as np
import math
# 数据点
data = [
1119.15,590,1091.45,580,1081.83,570,1072.21,560,1063.26,550,1053.62,540,1043.96,530,1034.28,520,1024.55,510,1014.82,500,1005.76,490,995.967,480,985.434,470,975.562,460,965.647,450,955.686,440,945.578,430,934.792,420,924.668,410,913.756,400,903.51,390,892.459,380,881.333,370,869.767,360,858.411,350,846.75,340,833.258,330,819.291,320,802.14,310,781.727,300,753.795,290,709.608,280,642.965,270,

]
plt.figure(figsize=(16.4, 5.9))

# 将数据点拆分为X和Y轴
x = data[0::2]
y = data[1::2]
y = [590 - i for i in y]  # Y轴翻转


# 使用最小二乘法拟合直线
A = np.vstack([x, np.ones(len(x))]).T
m, c = np.linalg.lstsq(A, y, rcond=None)[0]
print(f"Fitted line: y = {m}x + {c}")

# 画出拟合的直线
x_fit = np.array([min(x), max(x)])
y_fit = m * x_fit + c

thetas = []
for i in range(1, len(x)):
    theta = (
        math.atan(
            i * 590 / 72 / (x[i] - x[0] + 1e-5)
        )
        / math.pi
    )
    theta = theta if theta > 0 else 1 - abs(theta)
    thetas.append(theta)
theta_far = sum(thetas) / len(thetas)
print("theta_far",theta_far)
# 画出原点是X[0],Y[0] 角度为thetas的直线
# 计算直线的终点坐标
x_start = x[0]
y_start = y[0]
length = 1000  # 直线的长度，可以根据需要调整

x_end = x_start + length * math.cos(theta_far * math.pi)
y_end = y_start + length * math.sin(theta_far * math.pi)

# 绘制直线
plt.plot([x_start, x_end], [y_start, y_end], 'g', label='Theta line')
plt.legend()

# 绘制曲线
plt.plot(x, y,'r', marker='o')
plt.plot(x_fit, y_fit, 'r', label='Fitted line')

################################################################################
# # 将数据点拆分为X和Y轴
# x = data[0::2]
# y = data[1::2]

# filtered_data = [(xi, yi) for xi, yi in zip(x, y) if 0 <= xi <= 1640 and 0 <= yi <= 590]
# x, y = zip(*filtered_data)

# # 对 x 和 y 进行排序
# sorted_indices = np.argsort(y)
# x = np.array(x)[sorted_indices]
# y = np.array(y)[sorted_indices]

# # 创建新的Y轴，差值固定为590/72
# fixed_diff = 590 / 72 * -1
# y_max = max(y)
# y_min = min(y)
# new_y = np.arange(y_max,y_min, fixed_diff)

# # 重新计算X值
# new_x = np.interp(new_y, y, x)

# # Y轴翻转
# new_y = [590 - yi for yi in new_y]
# # 打印delta x
# delta_x = np.diff(new_x)
# print("delta_x",delta_x)
# # 绘制曲线
# plt.plot(new_x, new_y, marker='x')




plt.ylim(0, 590)  # 设置Y轴范围
plt.xlim(0, 1640)  # 设置X轴范围
plt.grid(True)
plt.show()